<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import StepsForm from "./components/steps-form.vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getTextColor } from "@/utils/index";
import { ElMessage, ElMessageBox, ElDrawer } from "element-plus";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import { addGoods, delGoods, getGoodsList, updateGoods } from "@/api/goods";
import { getCateTree } from "@/api/good-cate";
import { getTags } from "@/api/tag-management";

defineOptions({
  name: "Goods"
});

const formRef = ref();
const stepsFormRef = ref(); // 步骤表单
const tableRef = ref();
const treeRef = ref();
const drawerVisible = ref(false);
const drawerTitle = ref("");
const formData = reactive({
  name: "",
  price: 0,
  stock: 0,
  sales: 0,
  brand: "",
  category_id: null,
  main_image: "",
  description: "",
  status: true,
  images: [],
  detail_html: "",
  tags: [],
  salePrice: 0,
  sort: 0
});

// 定义一个初始的 formData 对象，用于重置
const initialFormData = {
  name: "",
  price: 0,
  stock: 0,
  sales: 0,
  brand: "",
  category_id: null,
  main_image: "",
  description: "",
  images: [],
  detail_html: "",
  status: true,
  tags: [],
  salePrice: 0,
  sort: 0
};

const cateName = ref("");
const form = reactive({
  name: "",
  status: "",
  category_id: null,
  brand: "",
  tag_ids: [], // 改为数组形式，用于多选标签
  min_price: undefined, // 单位：分
  max_price: undefined // 单位：分
});
const loading = ref(false);
const dataList = ref([]);
const cateTree = ref([]);
const selectedNum = ref(0);
const selectedRows = ref([]);
const pagination = ref({
  total: 0,
  pageSize: 10,
  currentPage: 1
});

// 品牌和标签选项
const brandOptions = ref([
  { label: "耐克", value: "耐克" },
  { label: "阿迪达斯", value: "阿迪达斯" },
  { label: "李宁", value: "李宁" },
  { label: "安踏", value: "安踏" }
]);
const tagOptions = ref([]);

const getList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      name: form.name,
      status: form.status,
      category_id: form.category_id,
      brand: form.brand
    };

    // 处理标签ID列表：将数组转为逗号分隔的字符串
    if (form.tag_ids && form.tag_ids.length > 0) {
      params.tag_ids = form.tag_ids.join(",");
    }

    // 处理价格区间（单位：分）
    if (form.min_price !== undefined && form.min_price !== null) {
      params.min_price = form.min_price; // 元转分
    }
    if (form.max_price !== undefined && form.max_price !== null) {
      params.max_price = form.max_price; // 元转分
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === "" || params[key] === null) {
        delete params[key];
      }
    });
    console.log("params", params);
    const { code, data, message, total } = await getGoodsList(params);
    if (code !== 200) {
      ElMessage.error(message);
      return;
    }
    dataList.value = data.list;
    pagination.value.total = total;
  } catch (e) {
    ElMessage.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

const fetchCateTree = async () => {
  const { code, data, message } = await getCateTree();
  if (code !== 200) {
    ElMessage.error(message);
    return;
  }
  cateTree.value = data;
};

// 获取标签列表
const fetchTags = async () => {
  try {
    const { code, data, message } = await getTags({
      status: 1, // 只获取启用的标签
      type: 1 // 商品标签类型
    });
    if (code !== 200) {
      ElMessage.error(message);
      return;
    }
    // 转换为选项格式
    tagOptions.value = (data.list || []).map(tag => ({
      label: tag.name,
      value: tag.id
    }));
  } catch (error) {
    console.error("获取标签列表失败:", error);
  }
};

const onSearch = () => {
  pagination.value.currentPage = 1;
  getList();
};

// 重置表单
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();

  // 手动重置无法通过 resetFields 重置的字段
  form.tag_ids = [];
  form.min_price = undefined;
  form.max_price = undefined;

  onSearch();
};
// 批量删除商品
const onbatchDel = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的商品");
    return;
  }

  const selectedNames = selectedRows.value.map(row => row.name).join("、");
  ElMessageBox.confirm(
    `是否确认删除选中的 ${selectedRows.value.length} 个商品：${selectedNames}？`,
    "批量删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true
    }
  )
    .then(async () => {
      try {
        // 提取选中商品的ID数组
        const ids = selectedRows.value.map(row => row.id);

        // 验证ids必须是非空数组
        if (!Array.isArray(ids) || ids.length === 0) {
          ElMessage.warning("请选择要删除的商品");
          return;
        }

        // 调用删除API（后端支持数组）
        const res = await delGoods({ ids });

        if (res.code === 200) {
          ElMessage.success(`成功删除 ${selectedRows.value.length} 个商品`);

          // 刷新列表
          await getList();

          // 清空选择
          tableRef.value?.clearSelection();
        } else {
          ElMessage.error(res.message || "批量删除失败");
        }
      } catch (error) {
        ElMessage.error("批量删除操作失败");
        console.error("批量删除错误:", error);
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};
// 删除单条商品
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`是否确认删除商品名称为${row.name}的这条数据`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delGoods({ ids: [row.id] })
      .then(res => {
        if (res.code === 200) {
          ElMessage.success("删除成功");
          onSearch();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      })
      .catch(error => {
        ElMessage.error("删除操作失败");
        console.error("删除错误:", error);
      });
  });
};

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  getList();
};

const handleSelectionChange = val => {
  selectedNum.value = val.length;
  selectedRows.value = val;
};

// 创建一个唯一的key来强制重新渲染组件
const formKey = ref(0);

// 重置表单的核心方法
const resetFormData = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    delete formData[key];
  });
  Object.assign(formData, JSON.parse(JSON.stringify(initialFormData)));

  // 强制重新渲染StepsForm组件
  formKey.value++;
};

const openDrawer = (title = "新增", row?: any) => {
  drawerTitle.value = title;

  // 1. 重置表单数据
  resetFormData();

  // 2. 如果是修改操作，则用行数据覆盖
  if (row) {
    console.log("修改row", row);
    // 使用深拷贝避免引用问题
    const rowData = JSON.parse(JSON.stringify(row));
    Object.assign(formData, rowData);
  }

  // 3. 打开抽屉
  drawerVisible.value = true;
};

const handleSubmit = async (data: any) => {
  console.log("步骤表单数据", data);

  try {
    let res;
    if (data.id) {
      res = await updateGoods(data);
      if ((res.code !== 200 && res.code !== 201) || !res.data) {
        ElMessage.error(res.message);
        return;
      }
      ElMessage.success("更新成功");
    } else {
      res = await addGoods(data);
      if ((res.code !== 200 && res.code !== 201) || !res.data) {
        ElMessage.error(res.message);
        return;
      }
      ElMessage.success("新增成功");
    }

    // 提交成功后关闭抽屉
    drawerVisible.value = false;
    await getList();
  } catch (error) {
    ElMessage.error("操作失败");
    console.error(error);
  }
};

// 抽屉关闭时的处理
const handleDrawerClose = (done: () => void) => {
  // 关闭时重置表单
  resetFormData();
  done();
};

const handleNodeClick = data => {
  form.category_id = data.id;
  onSearch();
};

onMounted(() => {
  fetchCateTree();
  fetchTags();
  getList();
});

watch(cateName, val => {
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
</script>

<template>
  <div class="main">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="head-container">
          <el-input
            v-model="cateName"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="treeRef"
            :data="cateTree"
            :props="{ label: 'label' }"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20">
        <el-form
          ref="formRef"
          :inline="true"
          :model="form"
          class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
        >
          <el-form-item label="商品名称：" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称" clearable class="w-[170px]!" />
          </el-form-item>
          <el-form-item label="商品分类：" prop="category_id">
            <el-select v-model="form.category_id" placeholder="请选择" clearable class="w-[130px]!">
              <el-option v-for="item in cateTree" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="品牌：" prop="brand">
            <el-select v-model="form.brand" placeholder="请选择品牌" clearable class="w-[140px]!">
              <el-option
                v-for="item in brandOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签：" prop="tag_ids">
            <el-select
              v-model="form.tag_ids"
              placeholder="请选择标签"
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              class="w-[140px]!"
            >
              <el-option
                v-for="item in tagOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="价格区间(元)：">
            <el-input-number
              v-model="form.min_price"
              :min="0"
              :max="form.max_price || 999999"
              :precision="2"
              placeholder="最低价"
              class="w-[130px]!"
            />
            <span style="margin: 0 8px">-</span>
            <el-input-number
              v-model="form.max_price"
              :min="form.min_price || 0"
              :max="999999"
              :precision="2"
              placeholder="最高价"
              class="w-[130px]!"
            />
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select v-model="form.status" placeholder="请选择" clearable class="w-[180px]!">
              <el-option label="已上架" value="1" />
              <el-option label="已下架" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :icon="useRenderIcon('ri/search-line')"
              :loading="loading"
              @click="onSearch"
            >
              搜索
            </el-button>
            <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)"> 重置 </el-button>
          </el-form-item>
        </el-form>

        <div class="p-4 bg-bg_color">
          <div class="flex justify-between items-center mb-4">
            <p class="font-bold">商品列表</p>
            <div>
              <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="openDrawer('新增')">
                新增商品
              </el-button>
              <el-button
                type="danger"
                :icon="useRenderIcon(Delete)"
                :disabled="selectedNum === 0"
                @click="onbatchDel"
              >
                批量删除
              </el-button>
            </div>
          </div>
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="dataList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="主图" width="100">
              <template #default="{ row }">
                <el-image
                  :src="row.main_image"
                  fit="cover"
                  class="w-16 h-16"
                  :preview-src-list="[row.main_image]"
                  preview-teleported
                  hide-on-click-modal
                  :scale="0.8"
                />
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name" width="100" show-overflow-tooltip />
            <el-table-column label="分类" prop="category_name" />
            <el-table-column label="品牌" prop="brand" />
            <el-table-column label="价格" prop="price" sortable />
            <el-table-column label="销量" prop="sales" sortable />
            <el-table-column label="状态">
              <template #default="{ row }">
                <el-tag :type="row.status ? 'success' : 'danger'">
                  {{ row.status ? "已上架" : "已下架" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="标签" width="180">
              <template #default="{ row }">
                <div v-if="row.tags && row.tags.length > 0" class="tags-container">
                  <el-tag
                    v-for="tag in row.tags.slice(0, 3)"
                    :key="tag.id"
                    :color="tag.color"
                    :style="{
                      backgroundColor: tag.color,
                      color: getTextColor(tag.color),
                      borderColor: tag.color,
                      marginRight: '4px',
                      marginBottom: '2px'
                    }"
                    size="small"
                  >
                    {{ tag.name }}
                  </el-tag>
                  <el-tooltip
                    v-if="row.tags.length > 3"
                    :content="`还有 ${row.tags.length - 3} 个标签`"
                    placement="top"
                  >
                    <el-tag size="small" type="info">+{{ row.tags.length - 3 }}</el-tag>
                  </el-tooltip>
                </div>
                <span v-else class="text-gray-400">暂无标签</span>
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stock" />
            <el-table-column label="创建时间" prop="create_time" width="180" sortable />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  :icon="useRenderIcon(EditPen)"
                  @click="openDrawer('修改', row)"
                >
                  修改
                </el-button>
                <el-button link type="danger" :icon="useRenderIcon(Delete)" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-show="pagination.total > 0"
            class="mt-4"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>

    <!--抽屉-->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="60%" :before-close="handleDrawerClose">
      <template #title>
        <div class="flex justify-between items-center">
          <p class="font-bold">{{ drawerTitle }}</p>
          <el-button type="text" @click="drawerVisible = false" />
        </div>
      </template>
      <StepsForm :key="formKey" ref="stepsFormRef" :form-inline="formData" @submit="handleSubmit" />
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
